<template>
  <el-drawer
    :model-value="isShowReceive"
    :title="drawerTitle"
    size="35%"
    @close="close"
    :close-on-click-modal="false"
  >
    <template #header="{}">
      <div class="flex items-center justify-start">
        <el-icon
          class="w-10 mr-2 cursor-pointer"
          v-if="isShowAdd"
          @click="returnReceive"
          ><ArrowLeftBold
        /></el-icon>
        <div class="flex items-center justify-center flex-1">
          <p>{{ drawerTitle }}</p>
        </div>
      </div>
    </template>
    <div class="flex justify-end mb-6" v-if="!isShowAdd && !isShowQR">
      <el-button
        :plain="true"
        class="plainButton"
        type="danger"
        @click="addPayer"
      >
        {{ $t("添加付款人") }}
      </el-button>
    </div>
    <el-card style="padding: 0 10px" v-if="!isShowAdd && !isShowQR">
      <h3 class="mb-4 font-bold text-large">
        {{ $t("设置完成后会生成收款链接进行收款") }}
      </h3>
      <el-form
        ref="receiveFormRef"
        :model="state.receiveInfo"
        label-width="100px"
        label-position="top"
        :rules="rules"
      >
        <el-form-item :label="$t('收款金额')" prop="amount">
          <el-input
            v-model="state.receiveInfo.amount"
            :placeholder="$t('请输入金额')"
            clearable
          />
        </el-form-item>
        <el-form-item :label="$t('收款币种')" prop="currency">
          <el-select
            v-model="state.receiveInfo.currency"
            :placeholder="$t('VA-请选择币种')"
            style="width: 100%"
          >
            <el-option
              v-for="item in state.currencyList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('付款人')" prop="payer_id">
          <el-select
            v-model="state.receiveInfo.payer_id"
            :placeholder="$t('VA-请选择付款人')"
            style="width: 100%"
            @change="payerChange"
            :popper-class="customPopperClass"
          >
            <el-option
              v-for="item in state.payerList"
              :key="item.payer_id"
              :label="item.name"
              :value="item.payer_id"
            />
            <el-option
              v-if="state.payerList.length < 1"
              :label="11"
              :value="false"
            >
              <template #default>
                <div class="flex flex-col items-center justify-center bankCard">
                  <div class="mb-2 payer">
                    <el-icon><Plus /></el-icon>
                    {{ $t("添加付款人") }}
                  </div>
                  <p>{{ $t("还未添加付款人") }}</p>
                </div>
              </template>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div v-if="state.receiveInfo.payer_id" class="mt-6">
        <div
          v-for="(item, index) in payInfoList"
          :key="index"
          class="detailRow"
          v-show="item.isShow"
        >
          <span class="rowName">{{ item.name }}</span>
          <span class="rowValue">{{ item.value }}</span>
        </div>
      </div>
      <el-button
        :plain="true"
        type="danger"
        class="w-full mt-6 plainButton btn"
        @click="submit(receiveFormRef)"
        v-loading="loading"
      >
        {{ $t("提交") }}
      </el-button>
    </el-card>

    <CreatePayer
      v-if="isShowAdd && !isShowQR"
      :isShowAddPayer="isShowAddPayer"
      @closeAddPayer="closeAddPayer"
    />
    <ReceiveQR
      v-if="isShowQR"
      :isShowQR="isShowQR"
      :pay_url="state.pay_url"
      :detailInfo="state.detailInfo"
      :receiveInfo="state.receiveInfo"
    />
  </el-drawer>
</template>
<script setup>
import { ref, watch, reactive, computed } from "vue";
import {
  GetVAPayerList,
  GetVaBankCurrency,
  VAOrdersPayment,
  GetVAOrdersPayInfo,
} from "@/api/VAAccount";
import CreatePayer from "./createPayer.vue";
import ReceiveQR from "./receiveQR.vue";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
const { t } = useI18n();

const props = defineProps({
  isShowReceive: {
    type: Boolean,
    default: false,
  },
  cardInfo: {
    type: Object,
    default: {},
  },
});

const isShowAdd = ref(false);

const state = reactive({
  receiveInfo: {},
  payerList: [],
  currencyList: [],
  payerInfo: {},
  pay_url: "",
  detailInfo: {},
});

const emit = defineEmits(["close", "submit"]);

watch(
  () => props.isShowReceive,
  (newVal) => {
    getPayerList();
    getVaBankCurrency();
  }
);

// 付款人列表
const getPayerList = async () => {
  const { list } = await GetVAPayerList({
    page: 1,
    pagesize: 999999,
  });
  state.payerList = list || [];
  findPayerInfo(state.receiveInfo.payer_id);
};

const payerChange = (val) => {
  if (!val) {
    isShowAdd.value = true;
    isShowAddPayer.value = true;
    drawerTitle.value = t("添加付款人");
    state.receiveInfo.payer_id = "";
  } else {
    findPayerInfo(val);
  }
};

const findPayerInfo = (id) => {
  const item = state.payerList.find((item) => item.payer_id === id);
  if (item) {
    state.payerInfo = item;
  }
};

const payInfoList = computed(() => {
  let arr = [
    {
      name: `${t("付款人姓名")}`,
      value: state.payerInfo.name || "--",
      isShow: true,
    },
    {
      name: `${t("付款人邮箱")}`,
      value: state.payerInfo.email || "--",
      isShow: true,
    },
    {
      name: `${t("付款人手机号")}`,
      value:
        `${state.payerInfo.area_code + "-" + state.payerInfo.phone}` || "--",
      isShow: true,
    },
    {
      name: `${t("付款人国家")}`,
      value: state.payerInfo.country || "--",
      isShow: true,
    },
    {
      name: `${t("付款人城市")}`,
      value: state.payerInfo.city || "--",
      isShow: true,
    },
    {
      name: `${t("付款人地址")}`,
      value: state.payerInfo.address || "--",
      isShow: true,
    },
  ];
  return arr;
});

// 币种
const getVaBankCurrency = async () => {
  try {
    const data = await GetVaBankCurrency();
    state.currencyList = data || [];
  } catch {}
};

const drawerTitle = ref(t("设置收款金额"));

const isShowQR = ref(false);

const loading = ref(false);

const receiveFormRef = ref();

// 提交
const submit = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      loading.value = true;
      VAOrdersPayment(state.receiveInfo)
        .then(async (res) => {
          state.pay_url = res.pay_url;
          const data = await GetVAOrdersPayInfo({
            order_no: res.order_no,
          });
          if (data) {
            state.detailInfo = data;
          }
          isShowQR.value = true;
          drawerTitle.value = t("收款");
          loading.value = false;
          emit("submit");
        })
        .catch(() => {
          loading.value = false;
        });
    }
  });
};

// 校验
const rules = computed(() => {
  return {
    amount: [{ required: true, message: t("请输入金额"), trigger: "change" }],
    currency: [{ required: true, message: t("请选择币种"), trigger: "change" }],
    payer_id: [
      { required: true, message: t("请选择付款人"), trigger: "change" },
    ],
  };
});

// 计算属性，根据条件返回不同的类名
const customPopperClass = computed(() => {
  return state.payerList.length < 1 ? "payerSelect" : "";
});

const isShowAddPayer = ref(false);

const close = () => {
  isShowAddPayer.value = false;
  isShowQR.value = false;
  isShowAdd.value = false;
  state.receiveInfo = {};
  if (receiveFormRef.value) {
    receiveFormRef.value.resetFields();
  }
  emit("close");
};

// 添加付款人
const addPayer = () => {
  isShowAdd.value = true;
  isShowAddPayer.value = true;
  drawerTitle.value = t("添加付款人");
};

// 返回选择付款人
const returnReceive = () => {
  isShowAdd.value = false;
  drawerTitle.value = t("设置收款金额");
};

// 关闭创建付款人
const closeAddPayer = (val) => {
  isShowAdd.value = false;
  if (val) {
    state.receiveInfo.payer_id = val;
  }
  getPayerList();
};
</script>
<style lang="scss" scoped>
.btn {
  border-radius: 20px;
}
.detailRow {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1rem;

  .rowName {
    min-width: 30%;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    color: #777;
  }

  .rowValue {
    word-break: break-all;
    text-align: right;
  }
}

.bankCard {
  border-radius: 10px;
  margin: 2%;
  padding: 2%;
}

.payerSelect .el-select-dropdown__item {
  height: 140px !important;
  padding: 0 5px 0 5px !important;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  .payer {
    min-width: 110px;
    padding: 0 6px;
    height: 80px;
    border: 1px solid #e54c5f;
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #e54c5f;
    .el-icon {
      font-size: 26px;
      font-weight: 700;
    }
  }
}
</style>
